from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, ValidationError
from typing import Any, Optional, Annotated

from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm

from controller.user import search_user, create_user, validator_user, get_password_hash
from models.user import User


class CommonResponseModel(BaseModel):
    code: int = 200
    data: Optional[Any] = None
    message: Optional[str] = None


router = APIRouter()


@router.get("/users/list", tags=["users"], response_model=CommonResponseModel)
async def read_users():
    item = [{"username": "John"}, {"username": "Jane"}]
    return CommonResponseModel(code=200,
                               data=item)


oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/users/login")


# 登录api
@router.post("/users/login", tags=["users"], summary="用户登录")
async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
    return validator_user(form_data.username, form_data.password)
    # return {"data": form_data}


@router.post("/users/singin", tags=["users"], summary="用户注册")
async def singin(user: User):
    try:
        if search_user(user.username):
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST, detail="User already registered")
        user.password = get_password_hash(user.password)
        create_user(user.model_dump())
        return CommonResponseModel(code=200,
                                   data="",
                                   message="User registered successfully")
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
